<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Library\Common;
use App\Service\AftersaleService;
use App\Service\AftersaleSetService;
use Psr\Http\Message\ResponseInterface;
use Hyperf\Di\Annotation\Inject;

/**
 * 售后单
 * Class AftersaleController
 * @package App\Controller
 */
class AftersaleController extends AbstractController
{

    /**
     * @Inject
     * @var AftersaleSetService
     */
    private $afSet;

    /**
     * @Inject
     * @var AftersaleSetService
     */
    private $aftersaleSet;

    /**
     * @Inject
     * @var AftersaleService
     */
    private $af;

    /**
     * 获取登录用户ID
     * @return int
     */
    public function get_user_id(): int
    {
        return (int)$this->request->getHeaderLine('admin_id') ?? 0;
    }

    /**
     * 获取可申请售后商品列表(有效订单列表)
     * @return ResponseInterface
     */
    public function getCanAfList(): ResponseInterface
    {
        $user_id = $this->get_user_id();
        $type = (int)$this->request->input('type', 0);
        $keyword = (string)$this->request->input('keyword', '');
        $list = $this->paginate($this->af->getAfList($user_id, $type, $keyword))->toArray();
        // 商品订单之间存在相同的售后类型可以进行批量申请

        foreach ($list['data'] as $k => &$datum) {
            $datum['can_together'] = 0;
            $type_pool = [];
            if (!empty($datum['with_can_apply_food_af_products'])) {
                $datum['with_can_apply_af_products'] = $datum['with_can_apply_food_af_products'];
                unset($datum['with_can_apply_food_af_products']);
            }
            // 虚拟产品名称及图片
            $datum['virtual_form_info_arr'] = empty($datum['virtual_form_info']) ? [] : json_decode($datum['virtual_form_info'], true);
            if ($datum['order_style'] == 2) {
                $datum['sku_name'] = date("m月d日,H:i", $datum['virtual_form_info_arr']['date_time']) . ',' . $datum['virtual_form_info_arr']['people_num'] . "人," . ($datum['virtual_form_info_arr']['is_vip'] ? "包间" : "大厅");
                $datum['sku_img'] = $datum['virtual_form_info_arr']['logo'] ?? "";
            }
            foreach ($datum['with_can_apply_af_products'] as &$with_product) {
                // 判断是否可以批量申请（一个订单中根据行业：查询支持的售后类型 支持的售后类型）AB可批量申请
                $with_product['apply_types'] = empty($with_product['support_af_types']) ? [] : explode(',', trim($with_product['support_af_types'], ','));
                if (empty($type_pool)) {
                    foreach ($with_product['apply_types'] as $apply_type) {
                        $type_pool[] = $apply_type;
                    }
                } else {
                    foreach ($with_product['apply_types'] as $apply_type) {
                        if (in_array($apply_type, $type_pool)) {
                            $with_product['can_together'] = 1;
                        }
                    }
                }
            }
        }
        return $this->jsonResponse->success($list);
    }

    /**
     * 可申请订单详情
     * @return ResponseInterface
     */
    public function canApplyDetails(): ResponseInterface
    {
        $user_id = $this->get_user_id();
        $type = (int)$this->request->input('type', 0);
        $order_id = (int)$this->request->input('order_id', 0);
        $details = $this->af->getAfList($user_id, $type, "", $order_id)->first();
        if (empty($details)) {
            return $this->jsonResponse->success([], '详情获取失败');
        }
        $return = $details->toArray();
        $return['can_together'] = $af_no_reason_duration = 0;
        $type_pool = [];
        if (!empty($return['with_can_apply_food_af_products'])) {
            $return['with_can_apply_af_products'] = $return['with_can_apply_food_af_products'];
            unset($return['with_can_apply_food_af_products']);
        }
        foreach ($return['with_can_apply_af_products'] as &$with_product) {
            // 判断是否可以批量申请（一个订单中根据行业：查询支持的售后类型 支持的售后类型）AB可批量申请
            $with_product['apply_types'] = empty($with_product['support_af_types']) ? [] : explode(',', trim($with_product['support_af_types'], ','));
            if (in_array(0, $with_product['apply_types'])) {
                if ($with_product['af_no_reason_duration'] > 0) {
                    if ($af_no_reason_duration == 0) {
                        $af_no_reason_duration = $with_product['af_no_reason_duration'];
                    } elseif ($af_no_reason_duration > $with_product['af_no_reason_duration']) {
                        $af_no_reason_duration = $with_product['af_no_reason_duration'];
                    }
                }
            }
            if (empty($type_pool)) {
                foreach ($with_product['apply_types'] as $apply_type) {
                    $type_pool[] = $apply_type;
                }
            } else {
                // 任何两个商品有共同的售后类型就可以批量神奇
                foreach ($with_product['apply_types'] as $apply_type) {
                    if (in_array($apply_type, $type_pool)) {
                        $return['can_together'] = 1;
                    }
                    $type_pool[] = $apply_type;
                }
            }
        }
        $return['all_support_types'] = array_merge(array_unique($type_pool));
        // 支持的售后原因列表
        $return['af_reasons'] = $this->afSet->getAfReason($return['all_support_types']);
        if (in_array(0, $return['all_support_types'])) {
            $return['af_reasons'][] = ['id' => 0, 'name' => $af_no_reason_duration . "天无理由退换货"];
        }
        return $this->jsonResponse->success($return, 'success');
    }

    /**
     * 售后申请确认
     * @return ResponseInterface
     */
    public function afApplyConfirm()
    {
        $user_id = (int)$this->getAdminId();
        if (empty($user_id)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '未登录');
        }
        return $this->jsonResponse->success($this->af->aftersaleConfirm($user_id));
    }

    /**
     * 申请售后单
     * @return ResponseInterface
     */
    public function afApply()
    {
        $user_id = (int)$this->getAdminId();
        if (empty($user_id)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '未登录');
        }
        $sn = $this->af->aftersaleApply($user_id);
        return $this->jsonResponse->success(['af_sn' => $sn]);
    }

    /**
     * 售后单详情
     * @return ResponseInterface
     */
    public function afDetails()
    {
        $user_id = (int)$this->getAdminId();
        if (empty($user_id)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '未登录');
        }
        $sn = (string)$this->request->input('af_sn', '');
        $details = $this->af->afDetails($sn, $user_id);
        $details['virtual_form_info_arr'] = empty($details['with_order']['virtual_form_info']) ? [] : json_decode($details['with_order']['virtual_form_info'], true);
        if (!empty($details['virtual_form_info_arr'])) {
            if ($details['af_order_style'] == 2) {
                $details['sku_name'] = date("m月d日,H:i", $details['virtual_form_info_arr']['date_time']) . ',' . $details['virtual_form_info_arr']['people_num'] . "人," . ($details['virtual_form_info_arr']['is_vip'] ? "包间" : "大厅");
                $details['sku_img'] = $details['virtual_form_info_arr']['logo'] ?? "";
            }
        }
        return $this->jsonResponse->success($details);
    }

    /**
     * 获取售后单列表
     * @return ResponseInterface
     */
    public function getAfList(): ResponseInterface
    {
        $user_id = (int)$this->getAdminId();
        if (empty($user_id)) {
            return $this->jsonResponse->success([], '未登录');
        }
        $type = (int)$this->request->input('search_type', 0);
        $type = ($type == AftersaleService::SEARCH_RECORD) ? AftersaleService::SEARCH_RECORD : AftersaleService::SEARCH_PROCESSING;
        $keyword = (string)$this->request->input('keyword', '');
        $list = $this->paginate($this->af->getAfList($user_id, $type, $keyword))->toArray();
        $af_sets = $this->afSet->getTimeTypeSet();
        $af_sets_days = array_column($af_sets, 'days', 'time_type');
        foreach ($list['data'] as &$item) {
            $item['count_down'] = "";
            // 回传单号时限：需要回传单号的
            if ($item['af_status'] == 2 && in_array($item['af_type'], [AftersaleService::TYPE_REFUND_P, AftersaleService::TYPE_SWAP, AftersaleService::TYPE_REPAIR])) {
                if (empty($item['user_response_sn'])) {
                    $dur = $item['check_time'] + 86400 * $af_sets_days[AftersaleSetService::TIME_TYPE_USER_RESPONSE] - time();
                    $dur = $dur < 0 ? 0 : $dur;
                } else {
                    $dur = $item['user_response_time'] + 86400 * $af_sets_days[AftersaleSetService::TIME_TYPE_AUTO_REFUND] - time();
                    $dur = $dur < 0 ? 0 : $dur;
                }
                $item['count_down'] = Common::formatSecondDuration($dur);
            }

            $item['voucher'] = empty($item['voucher']) ? [] : json_decode($item['voucher'], true);
            $item['apply_time'] = date('Y-m-d H:i:s', $item['apply_time']);
            $item['virtual_form_info_arr'] = empty($item['virtual_form_info']) ? [] : json_decode($item['virtual_form_info'], true);
            if (!empty($item['virtual_form_info_arr'])) {
                if ($item['af_order_style'] == 2) {
                    $item['sku_name'] = date("m月d日,H:i", $item['virtual_form_info_arr']['date_time']) . ',' . $item['virtual_form_info_arr']['people_num'] . "人," . ($item['virtual_form_info_arr']['is_vip'] ? "包间" : "大厅");
                    $item['sku_img'] = $item['virtual_form_info_arr']['logo'] ?? "";
                }
            }
        }
        return $this->jsonResponse->success($list, 'success!');
    }

    /**
     * 撤销售后
     * @return ResponseInterface
     */
    public function afCancel()
    {
        $user_id = (int)$this->getAdminId();
        if (empty($user_id)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '未登录');
        }
        $af_sn = (string)$this->request->input('af_sn', '');
        if (empty($af_sn)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '缺少参数');
        }
        $res = $this->af->afCancel($user_id, $af_sn);
        if (!$res) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '取消失败');
        }
        return $this->jsonResponse->success([], '操作成功');
    }

    /**
     * 用户回传单号
     * @return ResponseInterface
     */
    public function responseSN()
    {
        $user_id = (int)$this->getAdminId();
        if (empty($user_id)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '未登录');
        }
        if (!$this->af->responseSN($user_id)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '操作失败');
        }
        return $this->jsonResponse->success([], "操作成功");
    }

}